<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="账期：" prop="payment_days">
              <el-date-picker
                v-model="form.payment_days"
                type="months"
                placeholder="选择多个月"
                value-format="yyyy-MM"
                prefix-icon="false"
                @change="getArticleList"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="单号：" prop="order_sn">
              <el-input
                v-model.trim="form.order_sn"
                placeholder="原始单号/账单号"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="用户：" prop="uid">
              <change-user-input
                ref="changeUserInput"
                @sendValue="getUser"
                @zidname="uidName"
                @clear="clearUid"
              ></change-user-input>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
              <el-button @click="exportbuVisible = true">导出</el-button>
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-if="moredata">
                <el-form-item label="子账号：" prop="zid">
                  <el-select
                    v-model="form.zid"
                    placeholder="子账号"
                    class="wid220"
                    no-data-text
                    filterable
                    @change="getArticleList"
                  >
                    <el-option
                      v-for="(zid_time, index) in zid_name"
                      :key="index"
                      :label="zid_time.nickname"
                      :value="zid_time.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="账单日期：" prop="establishTime">
                  <el-date-picker
                    v-model="establishTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>
                <el-form-item label="单据类型：" prop="document_status">
                  <el-select
                    v-model.trim="form.document_status"
                    placeholder="对账状态"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value="0"></el-option>
                    <el-option
                      v-for="(typeList, index) in list.typeList"
                      :key="index"
                      :label="typeList"
                      :value="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="对账状态：" prop="statement_status">
                  <el-select
                    v-model.trim="form.statement_status"
                    placeholder="对账状态"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" :value="parseInt(0)"></el-option>
                    <el-option
                      v-for="(
                        account_status_list, index
                      ) in list.account_status_list"
                      :key="index"
                      :label="account_status_list"
                      :value="parseInt(index + 1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label="结算状态：" prop="status">
                  <el-select
                    v-model.trim="form.status"
                    placeholder="结算状态"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" :value="parseInt(0)"></el-option>
                    <el-option
                      v-for="(statusList, index) in list.statusList"
                      :key="index"
                      :label="statusList"
                      :value="parseInt(index + 1)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="结算日期：" prop="createTime">
                  <el-date-picker
                    v-model="createTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>
                <el-form-item label="配送日期：" prop="send_time">
                  <el-date-picker
                    v-model="form.send_time"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportbuVisible = true">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap">
          <div>
            <el-button @click="(userzname = '主账户'), settClick(1)">批量结算</el-button>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
          @row-dblclick="rowDblclick"
        >
          <el-table-column type="selection" :selectable="selectInit" align="center" />
          <div v-for="(item_show, index) of list.field" :key="index">
            <el-table-column
              label="原始单号"
              :min-width="tableWidth[hash+'related_order_sn'] || 200"
              prop="related_order_sn"
              v-if="item_show == 1"
            />
            <el-table-column
              label="配送日期"
              prop="order_send_time"
              :min-width="tableWidth[hash+'order_send_time'] || 150"
              v-if="item_show == 2"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.type == 1 && scope.row.order_bond">{{
                  parseTime(scope.row.order_bond.send_time, "{y}-{m}-{d}")
                }}</span>
                <span v-else-if="scope.row.type == 2"></span>
              </template>
            </el-table-column>
            <el-table-column
              label="单据类型"
              :min-width="tableWidth[hash+'type'] || 120"
              prop="type"
              v-if="item_show == 3"
            >
              <template slot-scope="scope"
                ><span :class="'type' + scope.row.type">{{
                  list.typeList[scope.row.type]
                }}</span></template
              >
            </el-table-column>
            <el-table-column
              v-if="item_show == 4"
              label="用户名称"
              prop="nickname"
              :min-width="tableWidth[hash+'nickname'] || 160"
            >
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.order_bond &&
                    scope.row.order_bond.zid_info &&
                    scope.row.order_bond.zid_info.nickname
                  "
                  >{{
                    scope.row.nickname +
                    "【 " +
                    scope.row.order_bond.zid_info.nickname +
                    " 】"
                  }}</span
                >
                <span
                  v-else-if="
                    scope.row.order_return_bond &&
                    scope.row.order_return_bond.order &&
                    scope.row.order_return_bond.zid_info &&
                    scope.row.order_return_bond.zid_info.nickname
                  "
                  >{{
                    scope.row.nickname +
                    "【 " +
                    scope.row.order_return_bond.zid_info.nickname +
                    " 】"
                  }}</span
                >
                <span v-else>{{ scope.row.nickname }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="账期"
              :width="tableWidth[hash+'payment_days'] || 120"
              prop="payment_days"
              v-if="item_show == 5"
            >
              <template slot-scope="scope">
                {{ scope.row.payment_days }}
              </template>
            </el-table-column>

            <el-table-column
              label="应收金额"
              :width="tableWidth[hash+'account_money'] || 120"
              prop="account_money"
              v-if="item_show == 6"
            />
            <el-table-column
              label="实收金额"
              :width="tableWidth[hash+'collect_money'] || 120"
              prop="collect_money"
              v-if="item_show == 7"
            />
            <el-table-column
              label="抹零金额"
              :width="tableWidth[hash+'zero_money'] || 120"
              prop="zero_money"
              v-if="item_show == 8"
            >
            </el-table-column>
            <el-table-column
              label="账单日期"
              :width="tableWidth[hash+'created_at'] || 120"
              prop="created_at"
              v-if="item_show == 9"
            >
              <template slot-scope="scope">
                {{ parseTime(scope.row.created_at, "{y}-{m}-{d}") }}
              </template>
            </el-table-column>
            <el-table-column
              label="账单号"
              prop="order_sn"
              :width="tableWidth[hash+'order_sn'] || 120"
              v-if="item_show == 10"
            />
            <el-table-column
              label="对账状态"
              :width="tableWidth[hash+'account_status'] || 120"
              prop="account_status"
              v-if="item_show == 11"
            >
              <template slot-scope="scope"
                ><span :class="'type' + scope.row.account_status">{{
                  list.account_status_list[scope.row.account_status]
                }}</span></template
              >
            </el-table-column>
            <el-table-column
              label="结算状态"
              :width="tableWidth[hash+'foot_status'] || 120"
              prop="foot_status"
              v-if="item_show == 12"
            >
              <template slot-scope="scope">
                <span :class="'order' + scope.row.status">{{
                  list.statusList[scope.row.status]
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="回单"
              prop="is_receipt"
              :width="tableWidth[hash+'is_receipt']"
              v-if="item_show == 13"
            >
              <template slot-scope="scope">
                <span
                  :style="{
                    color: scope.row.is_receipt == 1 ? '#19b098' : '#ff5a5a',
                  }"
                >
                  {{ scope.row.is_receipt == 1 ? "是" : "否" }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              prop="remark"
              :width="tableWidth[hash+'remark']"
              v-if="item_show == 14"
            />
          </div>
          <el-table-column
            label="管理操作"
            align="left"
            fixed="right"
            prop="operate"
            :width="tableWidth[hash+'operate'] || 240"
            class-name="main_hei handle"
            class="handle"
          >
            <template slot="header">
              <table-header-setting
                @openHeader="dialogFormVisible = true"
              ></table-header-setting>
            </template>
            <template slot-scope="scope">
              <router-link
                :to="'/financial/cash/see/' + scope.row.id + '/' + zname(scope)"
              >
                <el-link type="success">查看</el-link>
              </router-link>
              <router-link
                :to="
                  '/financial/cash/record/' +
                  scope.row.id +
                  '/' +
                  zname(scope) +
                  '/' +
                  scope.row.oid
                "
              >
                <!-- v-if="scope.row.type == 1" -->
                <el-link type="warning" v-if="scope.row.status == 0"
                  >对账</el-link
                >
              </router-link>
              <el-link
                type="primary"
                @click="
                  ((id = scope.row.id), (userzname = zname(scope))),
                    settClick(2)
                "
                v-if="scope.row.status != 2"
                >结算</el-link
              >
              <el-link
                style="color: rgb(17, 138, 178)"
                @click="exportOrderiInfo(scope)"
                v-if="
                  scope.row.status == 2 ||
                  scope.row.type == 2 ||
                  scope.row.status == 1
                "
                >导出</el-link
              >
              <!-- <el-link
                @click="print(scope)"
                v-if="
                  scope.row.status == 2 ||
                  scope.row.type == 2 ||
                  scope.row.status == 1
                "
                ><span v-if="scope.row.type == 1"> 打印 </span></el-link
              > -->

              <span v-if="scope.row.type == 1">
                <el-dropdown v-if="scope.row.status == 0">
                  <span class="el-dropdown-link" style="cursor: pointer">
                    更多<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item>
                      <el-link
                        style="color: rgb(17, 138, 178)"
                        @click="exportOrderiInfo(scope)"
                        >导出</el-link
                      >
                    </el-dropdown-item>
                    <el-dropdown-item
                      ><el-link @click="print(scope)" v-if="scope.row.type == 1"
                        >打印</el-link
                      ></el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div class="main_num boxdq mg-t-10">
          <div class="main_num_l box">
            <p>
              <em
                >注意：账单未对账也可结算；只有同一用户才能进行批量结算；账单结算后，不可再进行对账；</em
              >
            </p>
          </div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
        <!-- 批量结算 -->
        <el-dialog
          title="批量结算"
          :visible.sync="settFormVisible"
          class="main_dialog dialog1300"
        >
          <div class="pidding_20_30">
            <el-form
              :inline="false"
              :rules="rules"
              :model="info"
              class="demo-form-inline"
              ref="userListFrom1"
              label-width="0"
              key="userListFrom1"
            >
              <div class="dialog">
                <div class="main_xq">
                  <ul class="boxha">
                    <li>
                      用户名称：<span>{{
                        userzname == "主账户"
                          ? info.data.info.nickname
                          : info.data.info.nickname + "【" + userzname + "】"
                      }}</span>
                    </li>

                    <li>
                      应收金额：<span>{{ info.data.info.money }}</span>
                    </li>
                    <li>
                      已收金额：<span>{{ info.data.info.collect_money }}</span>
                    </li>
                    <li>
                      账期：<span>{{
                        info.data.info.payment_days.toString()
                      }}</span>
                    </li>
                    <li>
                      未收金额：<span>{{
                        info.data.info.uncollected_money
                      }}</span>
                    </li>
                    <li>
                      本次收款金额：<el-input
                        placeholder="本次收款金额"
                        v-model.lazy="totals.total"
                        @blur="totalSet"
                      >
                      </el-input>
                      <!-- <span>{{ total }}</span> -->
                    </li>
                    <li>
                      付款方式：
                      <el-form-item
                        prop="info_form.pay_type"
                        :rules="rules.pay_type"
                      >
                        <el-select
                          v-model.trim="info.info_form.pay_type"
                          placeholder="付款方式"
                          class="wid220"
                        >
                          <el-option
                            v-for="(pay_type_list, index) in info.data
                              .pay_type_list"
                            :key="index"
                            :label="pay_type_list"
                            :value="parseInt(index)"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </li>
                    <li>
                      <div class="Settlement">
                        全部结算：
                        <el-switch
                          class="mainor_switch"
                          active-text="开"
                          inactive-text="关"
                          v-model="SettlementAll"
                          active-color="#03A98E"
                          inactive-color="#DCDFE6"
                        >
                        </el-switch>
                        <el-popover
                          placement="top-start"
                          title="提示"
                          width="200"
                          trigger="hover"
                          content="开启时会全额结算，所有订单根据输入内容自动平账。关闭后可部分结算,当应付金额为负数时总抹零功能会被禁用"
                        >
                          <el-button
                            type="text"
                            slot="reference"
                            icon="el-icon-info"
                          ></el-button>
                        </el-popover>
                      </div>
                    </li>
                    <li>
                      本次抹零金额：
                      <el-input
                        placeholder="本次抹零总金额"
                        v-model.lazy="totals.zero_total"
                        @blur="zero_moneySet"
                        :disabled="
                          SettlementAll == false &&
                          info.data.info.uncollected_money < 0
                        "
                      >
                      </el-input>
                    </li>
                    <div class="clearfix"></div>

                    <li class="main_w100 marginTop15 boxha boxnr">
                      付款人：
                      <span class="main_xqs" style="width: 30%">
                        <el-form-item
                          label=""
                          prop="info_form.payee"
                          :rules="rules.payee"
                        >
                          <el-input
                            v-model.trim="info.info_form.payee"
                            placeholder="付款人"
                            clearable
                          ></el-input>
                        </el-form-item>
                      </span>
                    </li>
                    <li class="main_w100 marginTop15 boxha boxnr">
                      备注：
                      <span class="main_xqs" style="margin-left: 12px">
                        <el-form-item label="" prop="info_form.remark">
                          <el-input
                            v-model.trim="info.info_form.remark"
                            placeholder="备注"
                            clearable
                          ></el-input>
                        </el-form-item>
                      </span>
                    </li>
                    <li class="main_w100 marginTop15 boxha">
                      上传凭证(3张)：
                      <span class="main_xqs">
                        <div class="box main_xqi">
                          <div class="main_upImg">
                            <el-upload
                              :action="uploadPath"
                              list-type="picture-card"
                              :on-success="handSuccess"
                              :on-remove="handleRemove"
                              :limit="3"
                              :file-list="filelist"
                              :headers="{
                                Authorization: getToken(),
                              }"
                            >
                              <span slot="default">
                                <svg
                                  aria-hidden="true"
                                  class="main_page_svg"
                                  width="32"
                                  height="27"
                                >
                                  <use xlink:href="#icon-commodit_camera" />
                                </svg>
                              </span>
                            </el-upload>
                            <div class="clearfix"></div>
                          </div>
                        </div>
                      </span>
                    </li>
                  </ul>
                </div>
                <div class="main_table marginTop0">
                  <el-table
                    ref="multipleTable1"
                    v-loading="listLoading"
                    :data="info.data.list"
                    element-loading-text="加载中"
                    fit
                    highlight-current-row
                    key="multipleTable1"
                  >
                    <el-table-column
                      label="原始单号"
                      prop="related_order_sn"
                      width="140"
                      class-name="main_hei"
                    />
                    <el-table-column label="单据类型" width="90">
                      <template slot-scope="scope">{{
                        info.data.typeList[scope.row.type]
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      label="账单号"
                      prop="order_sn"
                      width="170"
                      class-name="main_hei"
                    />
                    <el-table-column
                      label="应收金额"
                      prop="account_money"
                      width="90"
                      class-name="main_hei"
                    />
                    <el-table-column
                      label="已收金额"
                      prop="collect_money"
                      width="90"
                      class-name="main_hei"
                    />
                    <el-table-column
                      label="抹零金额"
                      prop="zero_money_copy"
                      width="90"
                      class-name="main_hei"
                    />
                    <el-table-column
                      label="未收金额"
                      prop="uncollected_money"
                      width="90"
                      class-name="main_hei"
                    />
                    <el-table-column
                      label="本次收款金额"
                      prop="pay_money"
                      width="150"
                      class-name="main_hei"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'data.list.' + scope.$index + '.pay_money'"
                          :rules="rules.pay_money"
                          label-width="10px"
                          label=" "
                        >
                          <el-input
                            v-model.trim="scope.row.pay_money"
                            placeholder="本次收款金额"
                            class="wid110"
                            @blur="setzero_money(scope)"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="本次抹零金额"
                      prop="zero_amount"
                      width="150"
                      class-name="main_hei"
                    >
                      <template slot-scope="scope">
                        <el-form-item
                          :prop="'data.list.' + scope.$index + '.zero_money'"
                          :rules="rules.zero_money"
                          label-width="10px"
                          label=" "
                        >
                          <el-input
                            v-model.trim="scope.row.zero_money"
                            placeholder="抹零金额"
                            class="wid110"
                            @blur="setpay_money(scope)"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="剩余未收"
                      width="90"
                      class-name="main_hei"
                    >
                      <template slot-scope="scope">{{
                        $toFixed(
                          scope.row.uncollected_money -
                            scope.row.pay_money -
                            scope.row.zero_money
                        )
                      }}</template>
                    </el-table-column>
                    <el-table-column
                      label="备注"
                      prop="remark"
                      width="200"
                      class-name="main_hei"
                    >
                      <template slot-scope="scope">
                        <el-form-item label-width="0" label="">
                          <el-input
                            v-model.trim="scope.row.remark"
                            placeholder="备注"
                            class="wid180"
                          ></el-input>
                        </el-form-item>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer">
            <span class="footer_red">合计:￥{{ total }}</span>
            <el-button type="primary" @click="settupmine" v-repeatClick
              >结 算</el-button
            >
          </div>
        </el-dialog>
        <!-- 表头设置 -->
        <el-dialog
          title="表头设置"
          :visible.sync="dialogFormVisible"
          class="main_dialog dialog500"
        >
          <div class="set_sort">
            <div class="set_none_show">
              <el-checkbox-group v-model="type">
                <el-checkbox
                  v-for="(Header, index) in group"
                  :key="index"
                  :label="Header.id"
                  :disabled="Header.disabled"
                  >{{ Header.name }}</el-checkbox
                >
              </el-checkbox-group>
            </div>
            <div class="set_header_sort">
              <div class="set_sort_ab">
                <draggable
                  chosen-class="chosen"
                  v-model="group"
                  @start="onStart"
                  @end="onEnd"
                  animation="500"
                >
                  <transition-group>
                    <li
                      class="set_sort_ab_border"
                      v-for="item in group"
                      :key="item.id"
                    >
                      <div>
                        <span class="el-icon-d-caret"></span>
                        <span>{{ item.name }}</span>
                      </div>
                      <svg-icon icon-class="index_move" />
                    </li>
                  </transition-group>
                </draggable>
              </div>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="setupmine" v-repeatClick
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!-- 订单导出 -->
        <el-dialog
          title="货到付款账单导出"
          :visible.sync="exportbuVisible"
          class="main_dialog dialog500"
        >
          <div class="pidding_20_30">
            <p class="exptitle">选择导出时间</p>
            <el-date-picker
              v-model="exportTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="dateChange"
            >
            </el-date-picker>
            <el-tooltip
              class="item"
              effect="dark"
              content="时间范围只能选择两个月之内"
              placement="bottom"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            <p class="exptitle" style="padding-top: 10px">用户</p>
            <change-user-input
              ref="changeUserInput"
              @sendValue="
                (data) => {
                  export_uid = data.info.user_id;
                }
              "
              @zidname="exprot_uidName"
              @clear="clearExprotUid"
            ></change-user-input>
            <p class="exptitle" style="padding-top: 10px">子账号</p>
            <el-select
              v-model="export_zid"
              placeholder="子账号"
              class="wid220"
              no-data-text
              filterable
            >
              <el-option
                v-for="(zid_time, index) in export_zidname"
                :key="index"
                :label="zid_time.nickname"
                :value="zid_time.id"
              ></el-option>
            </el-select>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="exportbuVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleExport" v-repeatClick
              >确 定</el-button
            >
          </div>
        </el-dialog>
      </div>
      <!-- 打印子组件 -->
      <order-print
        ref="printTemplate"
        v-show="false"
        id="printname"
      ></order-print>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  offline_index,
  offline_paid,
  offline_getList,
  export_offline_info_order,
  export_offline_info,
  export_offline,
} from "@/api/financial/finacialCashOnDelivery";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime, exportMethod, getNowMonth } from "@/utils/index";
import rules from "@/rules/financial/financialReceivables";
import { uploadPath } from "@/api/currency";
import OrderPrint from "@/views/order/orderPrint.vue";
import draggable from "vuedraggable";
import { user_getMemberInfo } from "@/api/currency";
import { commodityHeader } from "@/options/headerSet.js";
//排序
import { field_getField } from "@/api/sort";
import { field_save } from "@/api/currency";
import { get } from "sortablejs";
import { debounce } from "@/utils/debounce";
import { fn } from "moment";
export default {
  mixins: [mixins],
  components: {
    OrderPrint,
    draggable,
  },
  computed: {
    total() {
      let zs = 0;
      let collected_now = 0;
      this.info.data.list.forEach((e) => {
        zs += parseFloat(this.$toFixed(parseFloat(e.pay_money)));
      });
      return zs ? this.$toFixed(zs) : 0;
    },
    zero_total() {
      let zs = 0;
      let collected_now = 0;
      this.info.data.list.forEach((e) => {
        zs += parseFloat(this.$toFixed(parseFloat(e.zero_money)));
      });
      return zs ? this.$toFixed(zs) : 0;
    },
    zname() {
      return function (scope) {
        let name =
          scope.row.type == 1
            ? scope.row.order_bond &&
              scope.row.order_bond.zid_info &&
              scope.row.order_bond.zid_info.nickname
              ? scope.row.order_bond.zid_info.nickname
              : "主账户"
            : scope.row.order_return_bond &&
              scope.row.order_return_bond.order &&
              scope.row.order_return_bond.zid_info &&
              scope.row.order_return_bond.zid_info.nickname
            ? scope.row.order_return_bond.zid_info.nickname
            : "主账户";
        return name;
      };
    },
  },
  watch: {
    "info.data.list": {
      handler(newVal, oldVal) {
        this.totals.zero_total = this.zero_total;
        this.totals.total = this.total;
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      // 验证
      rules,
      // 上传图片
      filelist: [],
      uploadPath,
      getNowMonth,
      // 时间
      parseTime,
      exportMethod,
      //设置全额结算
      SettlementAll: true,
      // 列表数据
      list: {
        list: [],
      },
      info: {
        data: {
          info: {
            uid: "",
            nickname: "",
            payment_days: "",
          },
          list: [],
          buyer: ["未分拣"],
          modeList: ["未分拣"],
          supplier: ["未分拣"],
          pay_type_list: ["未分拣"],
          typeList: ["未分拣"],
        },
        info_form: {
          uid: "",
          nickname: "",
          pay_type: null,
          payee: "",
          remark: "",
          pics: [],
        },
      },
      // 合计
      all: {
        order_money_all: "",
        account_money_all: "",
        diff_money_all: "",
        send_money_all: "",
      },
      id: "",
      userzname: "",
      type: 1,
      settFormVisible: false,
      listLoading: false,
      // 搜索
      form: {
        // payment_days: parseTime(new Date(), "{y}-{m}"),
        payment_days: "",
        order_sn: "",
        uid: "",
        account_start_time: "", //账单日期
        account_end_time: "",
        document_status: "", //单据状态
        statement_status: null, //对账状态
        status: null, //结算状态
        start_time: "", //结算日期
        end_time: "",
        zid: "",
        send_time: [], // 配送日期
      },
      zid_name: [],
      createTime: [],
      establishTime: [],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 全选
      selectArr: [],
      // 表头设置
      dialogFormVisible: false,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      exportTime: [],
      export_uid: "",
      export_zid: "",
      export_zidname: [],
      exportbuVisible: false,
      group: commodityHeader,
      type: [],
      totals: {
        total: this.total,
        zero_total: 0,
      },
    };
  },
  activated() {
    this.$nextTick(() => {
      this.getNumerical(210);
    });
    if (this.$route.params.name) {
      let name = this.$route.params.name;
      this.$refs["changeUserInput"].name = name;
    }
    if (this.$route.params.uid) {
      let uid = this.$route.params.uid;
      this.form.uid = uid;
      this.uidName(this.$route.params.uid, this.$route.params.zid);
    }
    if (this.$route.params.uid) {
      this.form.zid = this.$route.params.zid;
    }
    if (this.$route.params.status) {
      this.form.status = this.$route.params.status;
    }
    if (this.$route.params.payment_days) {
      this.form.payment_days = this.$route.params.payment_days;
    }
    // 列表
    this.offline_index();
    this.sort_data();
    this.$nextTick(() => {
      // myTable是表格的ref属性值
      if (
        this.$refs.multipleTable &&
        this.$refs.multipleTable.doLayout
      ) {
        this.$refs.multipleTable.doLayout();
      }
    });
  },
  mounted() {
    if (this.$route.params.name) {
      let name = this.$route.params.name;
      this.$refs["changeUserInput"].name = name;
    }
  },
  inject: ["reload"],
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      const scope = { row }
      this.$router.push('/financial/cash/see/' + row.id + '/' + this.zname(scope))
    },
    startGetting() {
      this.getSearchFor();
    },
    getSearchFor() {
      this.getArticleList();
    },
    onStart() {},
    onEnd() {},
    //排序
    sort_data() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { type: 15 }
      );
      field_getField(data).then((res) => {
        let arry = JSON.parse(res.data.info.sort);
        if (arry || arry.length) {
          this.group.sort((a, b) => {
            return arry.indexOf(a.id) - arry.indexOf(b.id);
          });
        }
      });
    },
    // 排序设置确认
    setupmine() {
      let arry = [];
      let arrys = [];
      this.group.map((e) => {
        arrys.push(e.id);
        this.type.map((p) => {
          if (e.id == p) {
            arry.push(e.id);
            return;
          }
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 15 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          type: 15,
          fields: JSON.stringify(arry),
          sort: JSON.stringify(arrys),
        }
      );
      field_save(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "设置成功",
            type: "success",
          });
          this.reload();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    //获取用户信息
    getUser(data) {
      let uid = data.info.user_id;
      this.form.uid = uid;
      this.form.zid = "";
      this.offline_index();
    },
    // 清除用户的uid
    clearUid() {
      this.form.uid = "";
      this.form.zid = "";
      this.zid_name = [];
    },
    clearExprotUid() {
      this.export_uid = "";
      this.export_zid = "";
      this.export_zidname = [];
    },
    //展示子账号
    uidName(uid, zid) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: uid }
      );
      user_getMemberInfo(data).then((res) => {
        if (res.errcode == 0) {
          if (!zid && zid !== 0) {
            this.form.zid = "";
            this.form.zid_name = null;
          }
          res.data.subAccount.map((e, ind) => {
            if (ind == 0) {
              e.id = 0;
              e.nickname = "主账号";
            }
          });
          res.data.subAccount.unshift({
            id: "",
            nickname: "所有",
          });
          this.zid_name = res.data.subAccount;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    exprot_uidName(uid) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: uid }
      );
      user_getMemberInfo(data).then((res) => {
        if (res.errcode == 0) {
          this.export_zid = "";
          this.export_zidname = null;
          res.data.subAccount.map((e, ind) => {
            if (ind == 0) {
              e.id = 0;
              e.nickname = "主账号";
            }
          });
          res.data.subAccount.unshift({
            id: "",
            nickname: "所有",
          });
          this.export_zidname = res.data.subAccount;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 订单差额 ？注释
    renderHeader_purchase(h, { column, $index }) {
      // 这里在最外层插入一个div标签
      return h("div", [
        // h即为cerateElement的简写
        // 在div里面插入span
        h("span", {
          // 表示内容
          domProps: {
            innerHTML: column.label,
          },
          on: {
            click: () => {
              console.log(`${column.label}   ${$index}`);
            },
          },
        }),
        h(
          "el-tooltip",
          {
            // 表示属性
            attrs: {
              effect: "dark",
              content: "注释：差异金额=下单金额-对账金额",
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    // 监听绑定全选不可勾选
    selectInit(row, index) {
      let flag = true;
      if (row.type == 1) {
        flag = true;
        row.status == 2 ? (flag = false) : "";
      } else if (row.type == 2) {
        flag = true;
        row.status == 2 ? (flag = false) : "";
      }
      return flag;
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 上传图片-删除
    handleRemove(file) {
      const i = this.info.info_form.pics.findIndex(
        (item) => item.path == file.path
      );
      this.info.info_form.pics.splice(i, 1);
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      this.info.info_form.pics.push({
        name: "",
        path: res.data.path,
        url: res.data.src,
      });
    },
    // 结算
    settClick(type) {
      this.info.info_form = {
        uid: "",
        nickname: "",
        pay_type: null,
        payee: "",
        remark: "",
        pics: [],
      };
      this.filelist = [];
      if (type == 1) {
        if (this.selectArr.length == 0) {
          this.$message.error("请勾选订单");
          return;
        }
      }
      this.type = type;
      let ids = type == 1 ? this.selectArr : [{ id: this.id }];
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: JSON.stringify(ids) }
      );

      offline_getList(data).then((res) => {
        if (res.errcode == 0) {
          res.data.list.forEach((e) => {
            e.pay_money = e.uncollected_money;
            e.zero_money_copy = e.zero_money;
            e.zero_money = 0;
          });
          this.info.data = res.data;
          this.settFormVisible = true;
          this.totals.total = this.total;
          this.totals.zero_total = this.zero_total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    settupmine() {
      this.$refs["userListFrom1"].validate((valid) => {
        if (valid) {
          this.$confirm("确定结算吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let info = JSON.parse(JSON.stringify(this.info));
              info.info_form.uid = info.data.info.uid;
              info.info_form.nickname = info.data.info.nickname;

              info.info_form.pics = info.info_form.pics
                .map((e) => e.path)
                .join(",");

              let arry = [];
              // 老版本提交,不支持多賬期
              // info.data.list.map(e => {
              //   arry.push({
              //     id: e.id,
              //     pay_money: e.pay_money,
              //     zero_money: e.zero_money,
              //     remark: e.remark
              //   });
              // });
              let dataInfo = {};
              info.data.list.forEach((item, index) => {
                let { payment_days } = item;
                if (!dataInfo[payment_days]) {
                  dataInfo[payment_days] = {
                    payment_days,
                    child: [],
                  };
                }
                dataInfo[payment_days].child.push({
                  id: item.id,
                  pay_money: item.pay_money,
                  zero_money: item.zero_money,
                  remark: item.remark,
                });
              });
              let list = Object.values(dataInfo);
              list.forEach((e) => {
                arry.push(e.child);
              });
              let data = Object.assign(
                {
                  sign: Md5(
                    objKeySort(Object.assign(apiUrl().name)) +
                      apiUrl().appsecret
                  ),
                },
                apiUrl().name,
                info.info_form,
                { list: JSON.stringify(arry) }
              );
              offline_paid(data).then((res) => {
                this.settFormVisible = false;
                if (res.errcode == 0) {
                  this.$message({
                    message: "结算成功",
                    type: "success",
                  });
                  this.offline_index();
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            })
            .catch(() => {});
        }
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.offline_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.form.payment_days = "";
      this.form.uid = "";
      this.clearUid();
      this.$refs["changeUserInput"].name = "";
      this.createTime = [];
      this.establishTime = [];
      this.offline_index();
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.offline_index();
    },
    changePage(page) {
      this.current.page = page;
      this.offline_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    offline_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      offline_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.type = res.data.field;
          this.all.account_money_all = res.data.account_money_all;
          this.all.send_money_all = res.data.send_money_all;
          this.all.diff_money_all = res.data.diff_money_all;
          this.all.order_money_all = res.data.order_money_all;
          this.totalCount = res.data.list.total;
          // 在数据更新后执行
          this.$nextTick(() => {
            // myTable是表格的ref属性值
            if (this.$refs.multipleTable && this.$refs.multipleTable.doLayout) {
              this.$refs.multipleTable.doLayout();
            }
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.payment_days = this.form.payment_days
        ? this.form.payment_days.toString()
        : "";
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      form.account_start_time = this.establishTime[0]
        ? this.establishTime[0]
        : "";
      form.account_end_time = this.establishTime[1]
        ? this.establishTime[1]
        : "";

      form.send_time = form.send_time.join("_");
      return form;
    },

    // 打印
    print(scope) {
      this.printid = scope.row.id;
      this.$refs.printTemplate.$emit("demo", {
        id: scope.row.id,
        type: "cash_delivery_order",
        nickname:
          this.zname(scope) == "主账户"
            ? scope.row.nickname
            : scope.row.nickname + "【" + this.zname(scope) + "】",
      });
    },
    exportOrderiInfo(scope) {
      let id = scope.row.id;
      let type = scope.row.type;
      let func = null;
      let file_name = "";
      if (type == 1) {
        // console.log("订单");]
        func = export_offline_info_order;
        file_name = "货到付款账单-订单";
      } else if (type == 2) {
        // console.log("退货单");
        func = export_offline_info;
        file_name = "货到付款账单-退货单";
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: id,
          nickname:
            this.zname(scope) == "主账户"
              ? scope.row.nickname
              : scope.row.nickname + "【" + this.zname(scope) + "】",
        }
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      func(data)
        .then((res) => {
          this.exportMethod(res, file_name, notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },
    // 导出
    handleExport() {
      if (this.exportTime.length == 0) {
        this.$message.warning("请选择需要导出的时间段");
        return;
      }
      let form = {
        start_time: "",
        end_time: "",
        uid: this.export_uid,
        zid: this.export_zid,
      };

      if (this.exportTime && this.exportTime.length > 0) {
        form.start_time = this.exportTime[0];
        form.end_time = this.exportTime[1];
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_offline(data).then((res) => {
        this.exportMethod(res, "货到付款账单", notify);
      });
      this.exportbuVisible = false;
      this.$nextTick(() => {
        this.exportTime = [];
        this.uid = "";
      });
    },
    // 日期选择
    dateChange(val) {
      let start = val ? new Date(val[0]).getTime() : 0;
      let end = val ? new Date(val[1]).getTime() : 0;
      let diff = start - end;
      if (Math.abs(diff) > 3600 * 1000 * 24 * 60) {
        this.$message.warning("选择时间跨度不能超过两个月");
        this.exportTime = this.getNowMonth();
      }
    },
    //设置零钱
    zero_moneySet(set) {
      let num = this.$toFixed(this.totals.zero_total);
      if (num == 0) {
        this.info.data.list.forEach((e) => {
          e.zero_money = 0;
        });
      }
      if (this.SettlementAll) {
        this.totals.total = this.$toFixed(
          this.info.data.info.uncollected_money - num
        );
        this.totalSet(set);
      }
      this.info.data.list.sort((a, b) => {
        return b.uncollected_money - a.uncollected_money;
      });

      this.info.data.list.forEach((e) => {
        if (e.uncollected_money - e.pay_money === 0) {
          e.zero_money = 0;
        } else if (
          e.uncollected_money - e.pay_money - num >= 0 &&
          (num >= 0 || this.SettlementAll == false)
        ) {
          e.zero_money = this.$toFixed(num);
          num = 0;
        } else {
          num = this.$toFixed(num - (e.uncollected_money - e.pay_money));
          e.zero_money = this.$toFixed(e.uncollected_money - e.pay_money);

          // e.zero_money = num
        }
      });
    },
    //自动设置收款金额
    setpay_money(scope) {
      if (this.SettlementAll) {
        console.log(scope.row);
        scope.row.zero_money = this.$toFixed(scope.row.zero_money);
        scope.row.pay_money = this.$toFixed(
          scope.row.uncollected_money - scope.row.zero_money
        );
      }
    },
    //自动生成抹零金额
    setzero_money(scope) {
      if (this.SettlementAll) {
        scope.row.pay_money = this.$toFixed(scope.row.pay_money);
        scope.row.zero_money = this.$toFixed(
          scope.row.uncollected_money - scope.row.pay_money
        );
      }
    },
    //设置总收款
    totalSet(set) {
      let num = +this.totals.total;
      if (num >= 0) {
        this.info.data.list.forEach((e) => {
          if (e.uncollected_money < 0) {
            num -= e.uncollected_money;
          }
        });
      }
      if (this.SettlementAll && set != 1) {
        this.totals.zero_total = this.$toFixed(
          this.info.data.info.uncollected_money -
            this.$toFixed(this.totals.total)
        );
        this.zero_moneySet(1);
      }
      this.info.data.list.sort((a, b) => {
        return b.uncollected_money - a.uncollected_money;
      });
      if (num < 0) {
        if (num < this.total) {
          this.totals.total = this.total;
        }
        this.info.data.list.forEach((e) => {
          if (e.uncollected_money - num <= 0) {
            e.pay_money = this.$toFixed(num);
            num = 0;
          } else {
            num = this.$toFixed(num - e.uncollected_money);
            e.pay_money = this.$toFixed(e.uncollected_money);
          }
        });
        return;
      }
      // if (num > this.info.data.info.money) {
      //   this.$message.error("输入数值过大，已设置为最大金额");
      //   this.totals.total = this.info.data.info.money;
      // }

      this.info.data.list.forEach((e) => {
        if (e.uncollected_money - num >= 0) {
          e.pay_money = this.$toFixed(num);
          num = 0;
        } else {
          num = this.$toFixed(num - e.uncollected_money);
          e.pay_money = e.uncollected_money;
        }
      });
    },
  },
  created() {},
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: 100%;
  }

  .main_dialog {
    .main_xq {
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 0;
      }
    }

    .main_table {
      /deep/.el-table__body-wrapper {
        overflow-y: auto;
      }
      /deep/.el-table--small td {
        padding-top: 0;
      }
      /deep/.el-form-item--small.el-form-item {
        margin-bottom: 16px;
        margin-top: 16px;
        margin-right: 0;
      }
    }
    .main_xq ul li {
      width: 33.33%;
      margin-top: 5px;
      margin-bottom: 5px;
      .main_xqs {
        width: 85%;
        display: block;
        text-align: left;
        /deep/.el-input--small {
          width: 100%;
        }
      }
    }
    .footer_red {
      font-size: 16px;
      color: red;
      margin-right: 10px;
    }
  }
}
// 支付状态
.type2 {
  color: $colour_red;
}
.type1 {
  color: $green;
}
// 订单状态
.order0 {
  color: $order_color4;
}
.order1 {
  color: $order_color1;
}

/deep/.main_table .el-table--small td.handle .cell {
  display: flex;
  flex-direction: row;
  align-items: center;
}
// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
  cursor: pointer;
}
/deep/.el-dialog {
  min-width: 560px !important;
}
/deep/.el-dialog__body {
  padding: 0 !important;
}
.pidding_20_30 {
  padding: 20px 20px 30px 20px;
}
.disflex {
  margin-left: 210px;
  /deep/ .el-input__inner {
    width: 180px;
  }
}
.Settlement {
  font-size: 15px;
  color: #555;
  /deep/ .el-button {
    border: none;
    /deep/ .el-button:hover {
      border: none;
    }
  }
  /deep/.el-button--text {
    color: #555;
  }
}
.boxha li {
  display: flex;
  align-items: center;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
